#include <iostream>
#include <WS2tcpip.h>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib")

int main() {
    // 初始化Winsock
    WSADATA wsData;
    WORD ver = MAKEWORD(2, 2);
    int wsOk = WSAStartup(ver, &wsData);
    if (wsOk != 0) {
        std::cerr << "无法初始化Winsock！错误代码：" << wsOk << std::endl;
        return 1;
    }

    // 创建socket
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET) {
        std::cerr << "无法创建socket！错误代码：" << WSAGetLastError() << std::endl;
        WSACleanup();
        return 1;
    }

    // 连接到服务端
    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(8085);
    inet_pton(AF_INET, "127.0.0.1", &hint.sin_addr);

    int connResult = connect(sock, (sockaddr *) &hint, sizeof(hint));
    if (connResult == SOCKET_ERROR) {
        std::cerr << "无法连接到服务端！错误代码：" << WSAGetLastError() << std::endl;
        closesocket(sock);
        WSACleanup();
        return 1;
    }

    // 输入要发送的字符串
    std::string userInput;
    std::cout << "请输入要发送的字符串：";
    std::getline(std::cin, userInput);

    // 发送数据到服务端
    int sendResult = send(sock, userInput.c_str(), userInput.size() + 1, 0);
    if (sendResult == SOCKET_ERROR) {
        std::cerr << "发送数据出错！错误代码：" << WSAGetLastError() << std::endl;
        closesocket(sock);
        WSACleanup();
        return 1;
    }

    // 接收服务端回复
    char buf[4096];
    ZeroMemory(buf, 4096);
    int bytesReceived = recv(sock, buf, 4096, 0);
    if (bytesReceived == SOCKET_ERROR) {
        std::cerr << "接收数据出错！错误代码：" << WSAGetLastError() << std::endl;
        closesocket(sock);
        WSACleanup();
        return 1;
    }

    // 输出服务端回复到控制台
    std::cout << "服务端回复：" << std::string(buf, 0, bytesReceived) << std::endl;

    // 关闭socket
    closesocket(sock);

    // 关闭Winsock
    WSACleanup();

    return 0;
}
